﻿using System;
using System.Collections;
using System.Collections.Generic;
using System.Windows.Forms;
using System.Drawing;
using CppProject;

namespace BackEndProcessorInterface
{
    public class MainMenu
    {
        #region Initialize top menu     

        private static  TopForm _topForm;
        private static EventModel _event;

        private static List<ProcessorFlag> _flags;
        //menu  &Task
        //menu &File
        private static readonly MenuItem fileMenuItem = new MenuItem("&Файл");
        //submenu
        private readonly MenuItem openFileMenuItem;
        private readonly MenuItem saveAsFileMenuItem;  
       
        //menu &View
        private static readonly MenuItem viewMenuItem = new MenuItem("&Вид");
        //submenu
        //TODO think about subview... 
        private readonly MenuItem southViewMenuItem;        
        private readonly MenuItem eastViewMenuItem;
        //menu &Settings
        private static readonly MenuItem settingMenuItem = new MenuItem("&Настройки");
        private readonly MenuItem ZoomInMenuItem;
        private readonly MenuItem ZoomOutMenuItem;

        //submenu
        private readonly MenuItem settingGraphicsMenuItem;
        private readonly MenuItem settingMouseRegion;
        private readonly MenuItem FlagMouseRegime;
        //menu &Help
        private static readonly MenuItem helpMenuItem =  new MenuItem("&Помощь");
        //submenu

        private readonly System.Windows.Forms.MainMenu mainMenu = new System.Windows.Forms.MainMenu(
            new[] { fileMenuItem, viewMenuItem, settingMenuItem, helpMenuItem });

       


        #endregion

        #region Initialize event 

        

        private void HandleZoom(object obj, EventArgs ea)
        {
            switch (((MenuItem)obj).Name)
            {
                case "buttonZoomAdd":
                    ZoomAdd();
                    break;
                case "buttonZommRemove":
                    ZoomRemove();
                    break;
            }
        }
        private static void _DrawItem(object obj, DrawItemEventArgs diea)
        {
            Image bitMap = null;
            switch (((MenuItem)obj).Name)
            {
                case "buttonZoomAdd":
                    bitMap = Properties.Resources.round_add;
                    break;
                case "buttonZommRemove":
                    bitMap = Properties.Resources.round_remove;
                    break;               
            }
            diea.DrawBackground();
            if (bitMap != null)
            {
                diea.Graphics.DrawImage(bitMap, diea.Bounds.X, diea.Bounds.Y);
                diea.Graphics.DrawString(((MenuItem) obj).Text, diea.Font, Brushes.Black,
                                         diea.Bounds.X + bitMap.Width + 2, diea.Bounds.Y);
            }
        }
        private static void _MeasureItem(object obj, MeasureItemEventArgs miea)
        {
            miea.ItemWidth = 100;
            miea.ItemHeight = 18;
        }
        private static void _MostTop(object obj, EventArgs ea)
        {
            if (obj is MenuItem)
            {
                var smi = (MenuItem)obj;
                smi.Checked = !smi.Checked;
                _topForm.ViewButton("toolStripButtonMostTop", smi.Checked);
                _topForm.TopMost = smi.Checked;
            }
        }
        private static void _BorderVisible(object obj, EventArgs ea)
        {
            if (obj is MenuItem)
            {
                var smi = (MenuItem)obj;
                smi.Checked = !smi.Checked;
                _topForm.ViewButton("toolStripButtonBorderEnable", !smi.Checked);
                _topForm._BorderVisible(smi.Checked);
                
            }
        }
        private static MenuItem CloneMenuItem(MenuItem source)
        {
            var dest =   source.CloneMenu();
            dest.Name = source.Name;
            dest.Checked = source.Checked;
        
            return dest;
        }
        private  static MenuItem[] CloneMenuItems(/*IEnumerable<MenuItem>*/ IEnumerable source)
        {
            var dest = new List<MenuItem>(); 
            var enumerator =  source.GetEnumerator();
            while (enumerator.MoveNext())
            {
                dest.Add(CloneMenuItem((MenuItem) enumerator.Current));
            }
            return dest.ToArray();
        }
        private static ContextMenu CreateContextMenu(IEnumerable source)
        {
            return new ContextMenu(CloneMenuItems(source));
        }
        #endregion

		private readonly CppController controller;

        public ContextMenu _rMenuItem { get; set; }
        public ContextMenu _lMenuItem { get; set; }

        public MainMenu(TopForm topForm, CppController cppController)       
        {
          _topForm = topForm;          
          _event = new EventModel(_topForm, cppController);
          controller = cppController;
          _flags = new List<ProcessorFlag>();
            
          saveAsFileMenuItem = new MenuItem("&Сохранить Как...");
              saveAsFileMenuItem.MenuItems.Add( new MenuItem(("txt-формат"),_event.FormatSaveFileClick){Name = "txt"});
              saveAsFileMenuItem.MenuItems.Add( new MenuItem(("data-формат"),_event.Plug/* _event.FormatSaveFileClick)*/));
             // saveAsFileMenuItem.MenuItems.Add( new MenuItem(("csv-формат"), _event.CsvFormatSaveFileClick));
              saveAsFileMenuItem.MenuItems.Add( new MenuItem(("xls-формат"), _event.FormatSaveFileClick){Name = "xls"});
             

          openFileMenuItem = new MenuItem("&Открыть");
          openFileMenuItem.MenuItems.Add(new MenuItem("&Настройки", _event.OpenFileClick, Shortcut.CtrlShiftS) { Name = "settings"});
          openFileMenuItem.MenuItems.Add(new MenuItem("&Файл постпроцессора", _event.OpenFileClick, Shortcut.CtrlShiftP) { Name = "proc" });
          openFileMenuItem.MenuItems.Add(new MenuItem("&Задача", _event.OpenFileClick, Shortcut.CtrlShift0) { Name = "task" });

          fileMenuItem.MenuItems.Add(new MenuItem("&Создать", _event.NewFileClick, Shortcut.CtrlN));
          fileMenuItem.MenuItems.Add(openFileMenuItem);
            fileMenuItem.MenuItems.Add(new MenuItem("-"));
          fileMenuItem.MenuItems.Add(new MenuItem("&Сохранить", _event.SaveFileClick, Shortcut.CtrlS));
          fileMenuItem.MenuItems.Add(saveAsFileMenuItem);
          fileMenuItem.MenuItems.Add(new MenuItem("&Сохранить Все", _event.SaveAllFileClick));
          fileMenuItem.MenuItems.Add(new MenuItem("-"));
          fileMenuItem.MenuItems.Add(new MenuItem("&Печать", _event.PrintFileClick, Shortcut.CtrlP));
          fileMenuItem.MenuItems.Add(new MenuItem("-"));
          fileMenuItem.MenuItems.Add(new MenuItem("&Выход", _event.ExitFileClick, Shortcut.AltF4));


          southViewMenuItem = new MenuItem("Включить панель логов", _event.ViewClick, Shortcut.Alt1) 
          {Name = "toolStripButtonPanelLog", Checked = true };        
          viewMenuItem.MenuItems.Add(southViewMenuItem);

          eastViewMenuItem = new MenuItem("Включить панель инструментов", _event.ViewClick, Shortcut.Alt2) 
          { Name = "toolStripButtonPanelRight", Checked = true };      
          viewMenuItem.MenuItems.Add(eastViewMenuItem);
          viewMenuItem.MenuItems.Add(new MenuItem("-"));
          var mi = new MenuItem("&Поверх всех окон",  _MostTop, Shortcut.Alt3);          
          viewMenuItem.MenuItems.Add(mi);
          mi = new MenuItem("&Выключить границы панелей", _BorderVisible, Shortcut.Alt4);
          viewMenuItem.MenuItems.Add(mi);

          settingMenuItem.MenuItems.Add(settingGraphicsMenuItem = new MenuItem("&Графические настройки"));

          settingGraphicsMenuItem.MenuItems.Add(new MenuItem("&Включить Оси", _event.CheckGraphicsSettings) { Name = "checkBoxAxis" });
          settingGraphicsMenuItem.MenuItems.Add(new MenuItem("&Вкл. Градиент", _event.CheckGraphicsSettings) { Name = "checkBoxMesh" });
          settingGraphicsMenuItem.MenuItems.Add(new MenuItem("&Вкл. Сеть МКЕ", _event.CheckGraphicsSettings) { Name = "checkBoxMeshFI" });
          settingGraphicsMenuItem.MenuItems.Add(new MenuItem("&Вкл. Изолинии", _event.CheckGraphicsSettings) { Name = "checkBoxIsoline" });
          settingGraphicsMenuItem.MenuItems.Add(new MenuItem("&Флаги", _event.CheckGraphicsSettings) { Name = "checkBoxFlags" });
          settingGraphicsMenuItem.MenuItems.Add(new MenuItem("-"));
          ZoomInMenuItem = new MenuItem("Приблизить", HandleZoom) { Name = "buttonZoomAdd", OwnerDraw = true };
          ZoomInMenuItem.DrawItem += _DrawItem;
          ZoomInMenuItem.MeasureItem += _MeasureItem;
          settingGraphicsMenuItem.MenuItems.Add(ZoomInMenuItem);
          ZoomOutMenuItem = new MenuItem("Уменьшить", HandleZoom) { Name = "buttonZommRemove", OwnerDraw = true };
          ZoomOutMenuItem.DrawItem += _DrawItem;
          ZoomOutMenuItem.MeasureItem += _MeasureItem;
          settingGraphicsMenuItem.MenuItems.Add(ZoomOutMenuItem);
          settingMenuItem.MenuItems.Add(mi = new MenuItem("&Сохр. графические настройки"));
          settingGraphicsMenuItem.MenuItems.Add(new MenuItem("-"));
          settingGraphicsMenuItem.MenuItems.Add(new MenuItem("&Получить градиент", _event.ScaleMinMaxValue) { Name = "getgrad" });
          settingGraphicsMenuItem.MenuItems.Add(new MenuItem("&Получить изолинии", _event.ScaleMinMaxValue) { Name = "getisol" });

          mi.MenuItems.Add((new MenuItem(("&Настройки цвета и изолиний(proc)"), _event.FormatSaveFileClick) {Name = "proc"}));
          mi.MenuItems.Add((new MenuItem(("&Настройки панели инструментов(xml)"), _event.SaveAllFileClick)));
          settingMenuItem.MenuItems.Add(new MenuItem("-"));

          settingMenuItem.MenuItems.Add(settingMouseRegion =  new MenuItem("&Режим мыши"));
          mi = new MenuItem("&Обычный режим", _event.ChooserMousePointer, Shortcut.CtrlM) { Name = "toolStripButtonMouseDefault", Checked = true, };        
          settingMouseRegion.MenuItems.Add( mi);
          FlagMouseRegime = new MenuItem("&Режим флажков", _event.ChooserMousePointer, Shortcut.CtrlShiftM) { Name = "toolStripButtonFlag" };
          settingMouseRegion.MenuItems.Add(FlagMouseRegime);         

          helpMenuItem.MenuItems.Add(new MenuItem("&Помощь",  _event.HelpShowClick, Shortcut.F1));
          helpMenuItem.MenuItems.Add(new MenuItem("&О Программме", _event.AboutClick, Shortcut.CtrlF1));
         
            _topForm.Menu = mainMenu;
        
        }
       public void SetGraphicsMenuItemCheck(int item,bool value)
       {          
           string status = "Enable" ;
           if (!value)  status = "Disable";
           settingGraphicsMenuItem.MenuItems[item].Checked = value;
           _topForm.SetGraphicsSetting(settingGraphicsMenuItem.MenuItems[item].Name, value);
           //debug
           _topForm.SetText(_event.PSDate, String.Format("{0} is {1}", settingGraphicsMenuItem.MenuItems[item].Name, status));          
       }
        public bool LoadInterfaceSettings(string filename)
        {
            if (System.IO.File.Exists(filename))
                return _event.LoadInterfaceSettings(filename);
            return false;
        }
        
        public ContextMenu CreateRithtContextMenu()
        {
            return  _lMenuItem =  CreateContextMenu(settingGraphicsMenuItem.MenuItems);
        }
        public ContextMenu CreateLeftContextMenu()
        {
            return  _rMenuItem =  CreateContextMenu(settingMouseRegion.MenuItems);
        }

        //debug
        /*
       public void GraphicsSettingApply(params bool[] param)
       { 
          var message = "\r\n";
         var inum =   param.GetEnumerator();
            while(inum.MoveNext())
                message += inum.Current + "\r\n";
            _topForm.SetTask(_event.PSDate, String.Format("Графические настройки : {0}", message));
       }
         * */
        public void SetTask(string message)
        {
            _topForm.SetTask(message);
        }
        public void ZoomAdd()
       {
           _topForm.SetText(_event.PSDate, "Zoom Add");
           controller.ZoomIn();
       }
       public void ZoomRemove()
       {
           _topForm.SetText(_event.PSDate, "Zoom Remove");
           controller.ZoomOut();
       }
       public void ViewSettings(int item, bool val)
       {
           viewMenuItem.MenuItems[item].Checked = val;
       }
       public void PaintMouseFlag(bool val)
       {
           _topForm.PaintMouseFlag(val);
       }
       public void MousePointerSettings(int item, bool val)
       {
           settingMouseRegion.MenuItems[item].Checked = val;           
           _topForm.SetText(_event.PSDate,String.Format("Chooser : {0} is {1} ",settingMouseRegion.MenuItems[item].Name,val));
           if(item == 1 )
           {
            if(val)
            {
                FlagMouseRegime.MenuItems.Add( new MenuItem("Добавить", _event.AddFlag));
                FlagMouseRegime.MenuItems.Add(new MenuItem("Удалить", _event.RemoveAllFlag));
            }
            else
                FlagMouseRegime.MenuItems.Clear();
           }

       }
        //Debug
       public void GetFlagOption(params bool[] iparam)
       {
           var pf = new ProcessorFlag(iparam);
           _topForm.SetText(_event.PSDate,String.Format("Опции флага: {0} успешно получены!",pf));
           _flags.Add(pf);
       }
        //Debug
       public void DeleteLastFlagOption()
       {
           if (FlagMouseRegime.MenuItems.Count > 0)
           {
              var aFlag = FlagMouseRegime.MenuItems[0];

               if (aFlag != null)
               {
                   aFlag.Enabled = true;
                   aFlag.Checked = false;
               }
           }
           if (_flags.Count > 0)
           {
               _flags.RemoveAt(_flags.Count - 1);
               _topForm.SetText(_event.PSDate, "Опции флага успешно удалены!");
           }
           else
               _topForm.SetText(_event.PSDate, "Количество флагов 0!");
       }
        //
        // Debug
        //      
       public void SetIsolineSettings(params double[] iparam)
       {
           string message = "\r\n";
           System.Collections.IEnumerator inum = iparam.GetEnumerator();
           while (inum.MoveNext())
               message += inum.Current + "\r\n";
           _topForm.SetText(_event.PSDate, String.Format("Параметры изолинийи: {0}", message));
       }
      
       


    }
}
